有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何每隔n秒在imageview中更改图像

我制作了一个数组,所有图像都是int,我想在imageView中每3秒更改一次这些图像,我尝试了所有我能找到的解决方案,但显示出一些错误,我无法解决

java文件(home.java)

/**
* Created by sukhvir on 17/04/2015.
*/
public class home extends 安卓.support.v4.app.Fragment {

    ImageView MyImageView;
    int[] imageArray = { R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5 };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * Inflate the layout for this fragment
        */
        return inflater.inflate(R.layout.home, container, false);
    }
}

xml文件(home.xml)

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:orientation="vertical" 安卓:layout_width="match_parent"
    安卓:layout_height="match_parent">

    <ImageView
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        安卓:id="@+id/imageView"
        安卓:layout_gravity="center_horizontal" />
</LinearLayout>

共 (2) 个答案

  1. # 2 楼答案

    要达到您的要求,最好的选择是使用^{}每3秒更改一次图像,如下所示

    // Declare globally
    private int position = -1;
    
    /**
     * This timer will call each of the seconds.
     */
    Timer mTimer = new Timer();
    mTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            // As timer is not a Main/UI thread need to do all UI task on runOnUiThread
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                        // increase your position so new image will show
                    position++;
                    // check whether position increased to length then set it to 0
                    // so it will show images in circuler
                    if (position >= imageArray.length)
                        position = 0;
                    // Set Image
                    MyImageView.setImageResource(imageArray[position]);
                }
            });
        }
    }, 0, 3000);
    // where 0 is for start now and 3000 (3 second) is for interval to change image as you mentioned in question